package com.bdit.ydcb.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bdit.ydcb.MainActivity;
import com.bdit.ydcb.R;
import com.bdit.ydcb.callback.DialogCallback;
import com.bdit.ydcb.model.LoginResult;
import com.bdit.ydcb.model.ServerResponse;
import com.bdit.ydcb.utils.Constants;
import com.bdit.ydcb.utils.SPUtils;
import com.bdit.ydcb.utils.Urls;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.store.CookieStore;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.vise.log.ViseLog;

import java.net.SocketTimeoutException;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

public class LoginActivity extends Activity implements View.OnClickListener{
    private static final String TAG = "LoginActivity";
    private EditText userNameEdit;
    private EditText passwordEdit;
    private ImageView remember_iv;
    private boolean isRemember=true;
    private Button loginButton;
    private Dialog mDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        findViewById();
        initData();
    }
    private void findViewById(){
        userNameEdit = (EditText) findViewById(R.id.username_et);
        passwordEdit = (EditText) findViewById(R.id.password_et);
        remember_iv = (ImageView) findViewById(R.id.remember_im);
        remember_iv.setOnClickListener(this);
        loginButton = (Button) findViewById(R.id.login_bt);
        loginButton.setOnClickListener(this);
    }
    private void initData(){
        Intent intent = getIntent();
        isRemember = (Boolean)SPUtils.get(Constants.LOGIN_IS_REMEMBER, true);
        if(isRemember){
            remember_iv.setImageResource(R.drawable.select_yes);
            String username = (String) SPUtils.get(Constants.LOGIN_USERNAME, "");
            String password = (String) SPUtils.get(Constants.LOGIN_PASSWORD, "");
            userNameEdit.setText(username);
            passwordEdit.setText(password);
        }else{
            remember_iv.setImageResource(R.drawable.select_no);
        }
        boolean relogin = (boolean) intent.getBooleanExtra("relogin", false);
        if(!relogin){
            checkJessionid();
        }

    }
    private void checkJessionid(){
        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        HttpUrl httpUrl = HttpUrl.parse(Urls.SERVER);
        List<Cookie> cookies = cookieStore.getCookie(httpUrl);
        if (cookies != null) {
            for(int i=0;i<cookies.size();i++){
                Cookie cookie = cookies.get(i);
                Log.d(TAG, "checkJessionid: "+cookie.name()+"-----"+cookie.value());
                if("jeeplus.session.id".equals(cookie.name())&&cookie.value()!=""){
                    /*Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();*/
                    login();
                }
            }
        }
    }
    private void changeRemember(){
        if(this.isRemember){
            this.isRemember = false;
            remember_iv.setImageResource(R.drawable.select_no);
        }else{
            this.isRemember = true;
            remember_iv.setImageResource(R.drawable.select_yes);
        }
    }
    private void login(){
        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        HttpUrl httpUrl = HttpUrl.parse(Urls.SERVER);
        List<Cookie> cookies = cookieStore.getCookie(httpUrl);
        if (cookies != null) {
            for(int i=0;i<cookies.size();i++){
                Cookie cookie = cookies.get(i);
                Log.d(TAG, "checkJessionid: "+cookie.name()+"-----"+cookie.value());

            }
        }
        final String username = userNameEdit.getText().toString().trim();
        final String password = passwordEdit.getText().toString().trim();
        if ("".equals(username)) {
            Toast.makeText(this,"请填写登录账号",Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(password)) {
            Toast.makeText(this,"请填写登录密码",Toast.LENGTH_SHORT).show();
            return;
        }

        OkGo.<ServerResponse<LoginResult>>post(Urls.LOGIN_URL)
                .tag(this)
                .params("username",username)
                .params("password",password)
                .params("mobileLogin",1)
                .params("rememberMe",true)
                .execute(new DialogCallback<ServerResponse<LoginResult>>(this) {
                    @Override
                    public void onStart(Request<ServerResponse<LoginResult>, ? extends Request> request) {
                       setDialogMessage("登录中...");
                        super.onStart(request);
                    }

                    @Override
                    public void onError(Response<ServerResponse<LoginResult>> response) {
                        ViseLog.e(response.getException());
                        Throwable throwable = response.getException();
                        ViseLog.d(throwable.getClass().getSimpleName());
                        if(throwable instanceof SocketTimeoutException){
                            Toast.makeText(LoginActivity.this,"请求超时，请检查网络",Toast.LENGTH_SHORT).show();
                        }
                        super.onError(response);
                    }

                    @Override
                    public void onSuccess(Response<ServerResponse<LoginResult>> response) {
                        ServerResponse<LoginResult> serverResponse=response.body();
                        LoginResult loginResult = serverResponse.data;
                      /*  Call call = response.getRawCall();
                        StringBuilder sb;
                        if (call != null) {
                            Headers requestHeadersString = call.request().headers();
                            Set<String> requestNames = requestHeadersString.names();
                            sb = new StringBuilder();
                            for (String name : requestNames) {
                                sb.append(name).append(" ： ").append(requestHeadersString.get(name)).append("\n");
                            }
                            Log.d(TAG, "onSuccess: heard "+sb.toString());
                        }*/
                        ViseLog.d(loginResult);
                        if(serverResponse.success){
                            SPUtils.put(Constants.LOGIN_IS_REMEMBER, isRemember);
                            SPUtils.put(Constants.LOGIN_USERNAME, username);
                            SPUtils.put(Constants.LOGIN_PASSWORD, password);
                            SPUtils.put(Constants.USER_ID,loginResult.getUserid());
                            SPUtils.put(Constants.USER_NAME,loginResult.getUsername());
                            HttpUrl httpUrl = HttpUrl.parse(Urls.SERVER);
                            Cookie.Builder builder = new Cookie.Builder();
                            Cookie cookie = builder.name("jeeplus.session.id").value(loginResult.JSESSIONID).domain(httpUrl.host()).build();
                            CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
                            cookieStore.saveCookie(httpUrl, cookie);
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }else{
                            Toast.makeText(LoginActivity.this,"账号或密码错误",Toast.LENGTH_SHORT).show();

                        }
                    }
                });



    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.remember_im:
                changeRemember();
                break;
            case R.id.login_bt:
                login();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
}
